import { https, qqmapKey, imgPrefix } from "@/config/app";
import { getWxOpenId, userLogin } from "@/api/index";
import { crowdUserInfo } from "@/api/user";
import { useUserInfoStore } from "@/stores/userInfo";
const userInfoStore = useUserInfoStore();

// 手机号脱敏
export const EncryptTel = (phone: string) => {
  let str = "";
  if (phone) {
    str = phone.replace(/(\d{3})\d*(\d{4})/, "$1****$2");
  }
  return str;
};

// 拨打电话
export const callPhone = (phoneNumber: string) => {
  if (phoneNumber) {
    uni.makePhoneCall({
      phoneNumber,
    });
  }
};

// 页面跳转
export const onPageJump = (pageUrl: any) => {
  uni.navigateTo({
    url: pageUrl,
  });
};

// 图片上传
export const uploadFilePromise = (url: any) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: https + "/common/upload",
      filePath: url,
      name: "file",
      header: {
        Authorization: "Bearer " + userInfoStore.token,
      },
      success: (res) => {
        let data = JSON.parse(res.data);
        if (data.code === 200) {
          resolve(data);
        }
      },
    });
  });
};

// 保留两位小数，去掉后面多余的0
export const toFixedWithoutTrailingZeros = (num: any) => {
  let result = num.toFixed(2);
  // 移除末尾不必要的0
  result = result.replace(/\.00$/, "");
  // 移除末尾多余的点
  result = result.replace(/\.0$/, "");
  return result;
};

// 登录
export const onLogin = (e: any, uToastRef: any) => {
  uni.login({
    provider: "weixin",
    success: function (res) {
      if (res.code) {
        const { code } = res;
        uni.showLoading({
          title: "登录中……",
        });
        getWxOpenId({ code })
          .then((res1) => {
            uni.hideLoading();
            userInfoStore.setOpenId(res1.data);
            if (e.detail.errMsg == "getPhoneNumber:ok") {
              // 获取用户信息
              getUserInfo(res1.data, e.detail.code, uToastRef);
            } else {
              uToastRef.value.show({
                type: "warning",
                message: "授权失败！",
              });
            }
          })
          .catch((err) => {
            uToastRef.value.show({
              type: "error",
              message: err,
            });
          });
      } else {
        uToastRef.value.show({
          type: "warning",
          message: "登录失败！",
        });
      }
    },
  });
};

// 登录获取并保存用户信息
export const getUserInfo = (openid: string, code: string, uToastRef: any) => {
  userLogin({ code, openid })
    .then(async (res) => {
      const { data } = res;
      userInfoStore.setToken(data.token);
      data.avatar = imgPrefix + data.avatar;
      userInfoStore.setUserInfo(data);
      // 1群众 2民警 3所领导
      if (data.userType == 2) {
        uni.redirectTo({
          url: "/pages/police/home/index",
        });
      } else if (data.userType == 3) {
        uni.redirectTo({
          url: "/pages/leader/home/index",
        });
      } else if (data.userType == 1) {
        // 已注册
        if (userInfoStore.userInfo.registerStatus == 1) {
          await getCrowdUserInfo(uToastRef);
          await uni.redirectTo({
            url: "/pages/crowd/home/index",
          });
        } else {
          uni.navigateTo({
            url: "/pages/register/register",
          });
        }
        // 手机号B并没有新生一个用户而是在手机号A的基础上修改，没有返回token，但是userId和userType均有值3，且值为原手机号A的值
      } else {
        uni.navigateTo({
          url: "/pages/register/register",
        });
      }
    })
    .catch((err) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};

// 获取群众个人信息
export const getCrowdUserInfo = async (uToastRef: any) => {
  crowdUserInfo({ crowdUserId: userInfoStore.userInfo.userId })
    .then((res: any) => {
      const { data } = res;
      userInfoStore.setCrowdInfo(data);
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
